const {
    KEY_NOTIFICATION_LOGIN_SUCCESS
} = require("../../static/keys/notification-keys");
const {
    saveStorage,
    readStorage,
    removeStorage
} = require("../utils/storageUtil")
const KEY_STORAGE_USERINFO = 'key_storage_userinfo';
const KEY_STORAGE_TOKEN = "key_storage_token";
const KEY_NOTIFICATION_USER_CHANGE = 'key_notification_user_change';

import UserModel from "../models/userModel.js"
import {
    addNormalNotificationObserver,
    postNotification,
    removeNotificationObserver
} from "../utils/notificationCenter.js";

function saveUserInfo(userInfo) {
    if (userInfo) {
        let currentUserInfo = readUserInfo(userInfo);
        if (currentUserInfo) {
            currentUserInfo = new UserModel({
                ...currentUserInfo,
                ...userInfo
            })
        } else {
            currentUserInfo = new UserModel(userInfo)
        }
        saveStorage(KEY_STORAGE_USERINFO, currentUserInfo);
        postNotification(KEY_NOTIFICATION_USER_CHANGE, currentUserInfo);
    } else {
        removeStorage(KEY_STORAGE_USERINFO);
        postNotification(KEY_NOTIFICATION_USER_CHANGE, null)
    }
}

function readUserInfo() {
    let userInfo = readStorage(KEY_STORAGE_USERINFO)
    return userInfo ? new UserModel(userInfo) : null;
}

function watchUserInfoChange(callback, observer) {
    let userInfo = readUserInfo();
    if (typeof callback == 'function') {
        callback(userInfo)
    }
    addNormalNotificationObserver(KEY_NOTIFICATION_USER_CHANGE, (result) => {
        if (typeof callback == 'function') {
            if (result) {
                callback(new UserModel(result))
            } else {
                callback(result)
            }
        }
    }, observer);

}

function removeUserInfoChangeWatch(observer) {
    removeNotificationObserver(KEY_NOTIFICATION_USER_CHANGE, observer);
}

function saveToken(token) {
    saveStorage(KEY_STORAGE_TOKEN, token)
}

function readToken() {
    return readStorage(KEY_STORAGE_TOKEN)
}

module.exports = {
    readToken,
    saveToken,
    saveUserInfo,
    readUserInfo,
    watchUserInfoChange,
    removeUserInfoChangeWatch
}